<?php

namespace App\Http\Controllers\Web;

use App\Models\Products;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use function PHPUnit\Framework\isEmpty;

class ProductsController extends Controller
{
    public function index(Request $request)
    {
        $size = $request->input('size', 10);
        $query = Products::query()->with('productsChildren');

        $name = $request->input("name");
        $type = $request->input("type");
        $query->when($name, function ($query) use ($name) {
            $query->where('name', "like", "%{$name}%");
        });
        if ($type || $type === '0') {
            $query->where('type', $type);
        }
        return $this->successPaginate($query->paginate($size));
    }

    public function requestData(Request $request)
    {
        $requestData = $this->validate($request, [
            'name' => 'required',
            'name_en' => 'nullable',
            'type' => 'required',
        ]);
        return $requestData;
    }

    public function show($id)
    {
        $product = Products::query()->findOrFail($id);
        return $this->success($product);
    }

    public function store(Request $request)
    {
        $product = new Products;
        $requestData = $this->requestData($request);
        $product->fill($requestData);
        $product->save();
        return $this->success($requestData);
    }

    public function update(Request $request, $id)
    {
        $product = Products::query()->findOrFail($id);
        $requestData = $this->requestData($request);
        $product->fill($requestData);
        $product->save();
        return $this->success($requestData);
    }

    public function destroy($id)
    {
        $product = Products::query()->findOrFail($id);
        $product->delete();
        return $this->success();
    }
}
